import express from 'express';
import path from 'node:path';
import * as cheerio from 'cheerio';

interface IListItem {
    skin_name: string;
    ename: number;
    cname: string;
    id_name: string;
}

// 请求英雄列表数据
async function requestForData() {
    const response = await fetch('https://pvp.qq.com/web201605/js/herolist.json');
    const jsonData = (await response.json()) as IListItem[];
    return jsonData;
}

const __dirname = import.meta.dirname;
const publicDir = path.resolve(__dirname, '../public');
const PORT = 8080;              // 端口号

const app = express();

const heroListPromise = requestForData();

// 静态资源目录
app.use(express.static(publicDir));


app.get('/search', async (req, res) => {
    const keyword = req.query.kw || '';
    const heroList = await heroListPromise;
    const hero = heroList.find(e => e.cname===keyword);
    if (!hero) {
        // 用户输入不正确
        res.json({
            code: 400,
            data: null,
        });
        return;
    }
    // 详情页url地址
    const detailPageUrl = `https://pvp.qq.com/web201605/herodetail/${hero.id_name}.shtml`;
    const response = await fetch(detailPageUrl);
    const bytes = await response.arrayBuffer();
    const decoder = new TextDecoder('gbk');
    const html = decoder.decode(bytes);
    const $ = cheerio.load(html);
    const result = $('.pic-pf-list').data('imgname') as string;
    const skinNameString = result.replaceAll(/&\d+/g, '').replaceAll(' ', '');
    const skinList = skinNameString.split('|');
    const prefixUrl = `https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/${hero.ename}/${hero.ename}-bigskin-#.jpg`;

    let key = 0;
    const urls = skinList.map((item, index) => {
         const url = prefixUrl.replace('#', (index+1).toString());
         return {
            key: ++key,
            name: item,
            url,
         };
    });
    res.json({
        code: 200,
        data: urls,
        hero: hero.cname,
    });
});

app.listen(PORT, () => {
    console.log(`服务启动成功：http://localhost:${PORT}`);
});
